package com.leetcode.first50;

/**
 * Created by weishaofei on 2018/11/24.
 */
public class LeetCode0003 {

    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        char[] chars = s.toCharArray();
        StringBuilder front = new StringBuilder();
        StringBuilder next = new StringBuilder();
        boolean appendFront = true;
        boolean appendNext = false;
        for (char ch : chars) {
            if (appendFront && front.indexOf(String.valueOf(ch)) == -1) {
                front.append(ch);
                continue;
            }
            if (appendFront && front.indexOf(String.valueOf(ch)) != -1) {
                appendFront = false;
                if (next.length() == 0) {
                    appendNext = true;
                }
            }
            if (appendNext && next.indexOf(String.valueOf(ch)) == -1) {
                if (next.length() == 0 && front.indexOf(String.valueOf(ch)) + 1 != front.length()) {
                    next = genNew(front, next, ch);
                }
                next.append(ch);
                continue;
            }
            if (appendNext && next.indexOf(String.valueOf(ch)) != -1) {
                if (front.length() >= next.length()) {
                    next = genNew(next, new StringBuilder(), ch);
                    next.append(ch);
                    continue;
                }
                front = next;
                next = genNew(next, new StringBuilder(), ch);
                next.append(ch);
                continue;
            }

        }
        return front.length() > next.length() ? front.length() : next.length();
    }

    private StringBuilder genNew(StringBuilder front, StringBuilder next, char ch) {
        if (front.indexOf(String.valueOf(ch)) + 1 < front.length()) {
            next.append(front.substring(front.indexOf(String.valueOf(ch)) + 1));
        }
        return next;
    }


    public static void main(String[] args) {
        LeetCode0003 lt3 = new LeetCode0003();
        int length = lt3.lengthOfLongestSubstring("abababab");
        System.out.println(length);

        length = lt3.lengthOfLongestSubstring("abcabcbb");
        System.out.println(length);

        length = lt3.lengthOfLongestSubstring("bbbbb");
        System.out.println(length);
        length = lt3.lengthOfLongestSubstring("pwwkew");
        System.out.println(length);

        length = lt3.lengthOfLongestSubstring("abac");
        System.out.println(length);
        length = lt3.lengthOfLongestSubstring("bbtablud");
        System.out.println(length);

    }
}
